// 项目用的请求（兼容项目的后端）

import Vue from "vue"
import axios from "axios"
import store from "@/store"
import { getToken, getCsrfToken } from "@/utils/auth"
import errorCode from "@/utils/errorCode"
import Utils from "@/libs/framework/util"
import Constant from "@/libs/framework/constant"
import { Notification, MessageBox, Message } from "element-ui"

const request = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: process.env.VUE_APP_BASE_API,
    // 超时
    timeout: 150000
})

// 设置默认post请求
request.defaults.method = 'post'
// 设置header 后端默认用application/json;charset=UTF-8（和框架不一样）
request.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        // 是否需要设置 token 和设置 token
        const isToken = (config.headers || {}).isToken === false;
        let token = getToken();
        if (token && !isToken) {
            config.headers["championsoftTokenAuthorization"] =
                "championsoft " + token;
        }

        let csrfToken = getCsrfToken();
        if (csrfToken && !isToken) {
            config.headers[Constant.token.csrfToken] = csrfToken;
        }

        return config;
    },
    (error) => {
        console.log(error);
        return Promise.reject(error);
    }
)

let toLogining = false;
// 响应拦截器
request.interceptors.response.use((res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    if (Utils.isString(code) && code != "default") {
        return res.data;
    }

    // 获取错误信息
    const fw = Vue.prototype.$framework;
    const msg = errorCode[code] || res.data.msg || errorCode["default"];

    if (code === 401 || code === 302) {
        if (!toLogining) {
            toLogining = true;
            MessageBox.confirm("登录状态已过期，您可以继续留在该页面，或者重新登录", "系统提示", {
                confirmButtonText: "重新登录",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                store.dispatch("LogOut").then(() => {
                    toLogining = false;
                    fw.redirect.login();
                }).catch(() => {
                    toLogining = false;
                })
            }).catch(() => {
                toLogining = false;
            })
        }
    } else if (code === 500) {
        Message({
            message: msg,
            type: 'error'
        })

        return Promise.reject(new Error(msg))
    } else if (code !== 200) {
        Notification.error({
            title: msg
        })

        return Promise.reject('error')
    } else {
        return res.data
    }
}, error => {
    let { message } = error

    if (message == "Network Error") {
        message = "后端接口连接异常"
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时"
    } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常"
    }
    Message({
        message: message,
        type: 'error',
        duration: 5 * 1000
    })

    return Promise.reject(error)
})

export default request
